<template>
  <div class="title">跨商协会合作配置</div>
  <BasicForm @register="register" />

  <div class="tip">合作资源初始化配置</div>
  <BasicTable
    @register="registerTable"
    @edit-end="handleEditEnd"
    @edit-cancel="handleEditCancel"
    :beforeEditSubmit="beforeEditSubmit"
    :pagination="false"
  >
    <template #price="{ record, index }">
      <InputNumber
        v-model:value="record.price2"
        placeholder="请输入"
        :min="0.01"
        :max="1000"
        style="margin-top: 10px"
        @change="onChangePrice(record, index)"
      >
        <template #prefix>
          <span>秘书处联络（￥）</span>
        </template>
      </InputNumber>
    </template>

    <template #percent="{ record, index }">
      <div>
        <InputNumber
          v-model:value="record.percent"
          placeholder="请输入"
          :min="0"
          :max="100"
          @change="onChangePercent(record, index)"
        >
          <template #addonAfter>
            <span>%</span>
          </template>
        </InputNumber>
      </div>
    </template>
  </BasicTable>

  <div class="action">
    <a-button style="margin-right: 10px" @click="handleReset">重置</a-button>
    <a-button type="primary" @click="handleSave" :loading="submitLoading">保存</a-button>
  </div>
</template>

<script setup lang="ts">
import { OrgPermissionData, OrgPermissionSave } from '@/api/institution/list';
import { BasicForm, useForm } from '@/components/Form/index';
import { BasicTable, useTable } from '@/components/Table';
import { inject, Ref, ref } from 'vue';
import { IOrgCooperationResourceConfigInfo } from '@/api/institution/model/listModel';
import { useMessage } from '@/hooks/web/useMessage';
import { InputNumber } from 'ant-design-vue';

const dataId = inject('dataId') as Ref<string | number>;
const dataSource = ref<IOrgCooperationResourceConfigInfo[]>();
const submitLoading = ref(false);
const { createMessage } = useMessage();

const getData = async () => {
  let res = await OrgPermissionData(dataId.value);
  setFieldsValue(res.orgCooperationConfigInfo);
  setTableData(res.orgCooperationResourceConfigInfo);

  dataSource.value = res.orgCooperationResourceConfigInfo;
};

getData();

const [register, { setFieldsValue, getFieldsValue, validate }] = useForm({
  schemas: [
    {
      field: 'isOpenCooperation',
      component: 'RadioGroup',
      label: '是否开通跨商协会合作',
      colProps: {
        span: 14,
      },
      componentProps: {
        suffix: '个',
        options: [
          {
            label: '立即开通',
            value: 0,
          },
          {
            label: '暂不开通',
            value: 1,
          },
        ],
      },
      itemProps: {
        extra: '温馨提示：跨商协会合作涉及分润，请引导客户完成支付认证后该功能才生效。',
        required: true,
        validateStatus: 'error',
      },
    },
    {
      field: 'freeCooperationNum',
      component: 'InputNumber',
      label: '合作组织数量',
      required: true,
      componentProps: {
        max: 10000,
        min: 0,
        addonAfter: '个',
      },
      colProps: {
        span: 14,
      },
    },
    {
      field: 'cooperationPrice',
      component: 'InputNumber',
      label: '合作名额单价',
      required: true,
      componentProps: {
        max: 10000,
        min: 0,
        addonAfter: '元/年',
      },
      colProps: {
        span: 14,
      },
    },
  ],
  autoFocusFirstItem: true,
  actionColOptions: {
    span: 24,
  },
  labelWidth: 200,
  showActionButtonGroup: false,
});

const [registerTable, { setTableData }] = useTable({
  // api: OrgPermissionData,
  // fetchSetting: {
  //   listField: 'orgCooperationResourceConfigInfo',
  // },
  // beforeFetch: () => dataId.value,
  columns: [
    {
      title: '资源',
      dataIndex: 'projectName',
    },
    {
      title: '是否开放',
      dataIndex: 'isOpen',
      edit: true,
      editComponent: 'Select',
      editComponentProps: {
        options: [
          {
            label: '是',
            value: 0,
          },
          {
            label: '否',
            value: 1,
          },
        ],
      },
    },
    {
      title: '单价',
      dataIndex: 'price',
      width: 300,
      slots: { customRender: 'price' },
    },
    {
      title: '给合作机构的佣金比例',
      dataIndex: 'percent',
      width: 300,
      slots: { customRender: 'percent' },
      // title: '给本机构的佣金比例',
      // dataIndex: 'percent',
      // edit: true,
      // editComponent: 'InputNumber',
      // editComponentProps: {
      //   placeholder: '请输入',
      //   suffix: '%',
      //   min: 0,
      //   max: 100,
      // },
    },
  ],
  canResize: false,
  showIndexColumn: false,
  bordered: true,
  afterFetch: (data: any) => {
    console.log('data--->', data);
    // setFieldsValue()
  },
});

function handleEditEnd({ record, index, key, value }: Recordable) {
  console.log(record, index, key, value);
  return false;
}

function handleEditCancel() {
  setTableData(dataSource.value as any);
}

async function beforeEditSubmit({ record, index }) {
  let item = dataSource.value && dataSource.value[index];
  dataSource.value?.splice(index, 1, {
    ...item,
    ...record,
  });
}

function onChangePrice(data, index) {
  console.log(data, index);
  let item = dataSource.value && dataSource.value[index];
  dataSource.value?.splice(index, 1, {
    ...item,
    ...data,
  });
}

function onChangePercent(data, index) {
  let item = dataSource.value && dataSource.value[index];
  dataSource.value?.splice(index, 1, {
    ...item,
    ...data,
  });
}

//   function onChangePrice2(data, index) {
//     let item = dataSource2.value && dataSource2.value[index];
//     dataSource2.value?.splice(index, 1, {
//       ...item,
//       ...data,
//     });
//   }
function handleReset() {
  getData();
}

async function handleSave() {
  await validate();

  submitLoading.value = true;
  await OrgPermissionSave({
    orgId: dataId.value,
    // tenantId: 1001,
    orgCooperationConfigInfo: getFieldsValue(),
    orgCooperationResourceConfigInfo: dataSource.value,
  });
  submitLoading.value = false;
  createMessage.success('保存成功');
}
</script>

<style lang="less" scoped>
.vben-basic-table {
  height: unset !important;
}
.ant-input-number-affix-wrapper {
  width: 100% !important;
}
.action {
  display: flex;
  justify-content: flex-end;
}

.title {
  font-weight: bold;
  font-size: 18px;
  padding: 20px 0;
}
.checkbox-single {
  text-align: left;
  margin-left: 100px;
}

.tip {
  position: relative;
  padding-left: 10px;
  font-size: 14px;
  font-weight: bold;
}
.tip::before {
  position: absolute;
  top: 0;
  left: 0;
  content: '*';
  color: #ff4d4f;
}
</style>
